package ar.edu.itba.it.pdc.httpParser.models;

import ar.edu.itba.it.pdc.configuration.models.Response;
import ar.edu.itba.it.pdc.httpParser.interfaces.Model;

public class HttpResponse extends HttpMessage implements Response{

	HttpStatusLine initialLine;
	
	private int size = -1;
	private String mediaType;

	
	public boolean isConnectionClose(){

		HttpVersion version = initialLine.getVersion();

		if (version == HttpVersion.ONE) {
			if (getHeaderValue("Connection") != null) {
				return getHeaderValue("Connection").toLowerCase().equals(
						"close");
			}
			return true;
		} else if (version == HttpVersion.ONEDOTONE) {

			if (getHeaderValue("Connection") != null) {
				return getHeaderValue("Connection").toLowerCase().equals(
						"close");
			}
			return false;
		}

		return false;
	}

	
	public boolean closeConnection(){
		if (initialLine.getStatusCode() == 204
				|| initialLine.getStatusCode() == 304
				|| initialLine.getStatusCode() > 100 
				&& (initialLine.getStatusCode() < 200) || getHeaderValue("Transfer-Encoding") != null
				&& "chunked".equals(getHeaderValue("Transfer-Encoding")
						.toLowerCase()) || getHeaderValue("Content-Length") != null) {
			return false;
		}
		return true;
	}
	
	@Override
	public Model getInitialLine() {
		return initialLine;
	}

	@Override
	public void setInitialLine(Model initialLine) {
		this.initialLine = (HttpStatusLine)initialLine;
		
	}


	@Override
	public int getSize() {
		if (size == -1) {
			size = this.getBodySize();
		}
		return size;
	}


	@Override
	public String getMediaType() {
		if (mediaType == null) {
			mediaType = this.getHeaderValue("Content-Type");
			int range = mediaType.indexOf(";");
			if (range != -1) {
				mediaType = mediaType.substring(0, range);				
			}
			if (mediaType == null) {
				mediaType = "";
			}
		}
		return mediaType;
	}
}
